#!/bin/bash
#!/bin/bash
set -eEuo pipefail
cd "$(dirname "$(readlink -f "$0")")"/..

########################################
# util functions
########################################

color_echo() {
  local color=$1
  shift

  # if stdout is the terminal, turn on color output.
  if [[ -t 1 || "${GITHUB_ACTIONS:-}" = true ]]; then
    printf "\e[1;%sm%s\e[0m\n" "$color" "$*"
  else
    echo "$*"
  fi
}

die() {
  (($# > 0)) || die "${FUNCNAME[0]} requires arguments! But no provided"

  color_echo "1;31" "Error: $*" >&2
  exit 1
}

log_then_run() {
  (($# > 0)) || die "${FUNCNAME[0]} requires arguments! But no provided"

  color_echo "1;36" "Run under work directory $PWD :" >&2
  color_echo "1;36" "$*" >&2
  "$@"
}

run_mvn() {
  log_then_run ./mvnw -V --no-transfer-progress dependency:tree "$@"
}

#############################################
# build with default dependency versions
#############################################

run_mvn clean package
run_mvn package -P enable-ttl-agent-for-test

#############################################
# build with previous log4j2 versions
#############################################

CURRENT_LOG4J2_MINOR_VERSION=$(
  awk -F'</?log4j2\\.version>' '/<log4j2\.version>.*<\/log4j2\.version>/{print $2}' pom.xml |
    awk -F'\\.' '{print $2}'
)
readonly CURRENT_LOG4J2_MINOR_VERSION

readonly PREVIOUS_LOG4J2_VERSIONS_TEST_COUNT=5

for ((minor_version = CURRENT_LOG4J2_MINOR_VERSION - PREVIOUS_LOG4J2_VERSIONS_TEST_COUNT; minor_version < CURRENT_LOG4J2_MINOR_VERSION; minor_version++)); do
  log4j2_version="2.$minor_version.0"

  run_mvn surefire:test -Dlog4j2.version=$log4j2_version
  run_mvn dependency:properties surefire:test -P enable-ttl-agent-for-test -Dlog4j2.version=$log4j2_version
done

#############################################
# build with slf4j v2.x
#############################################

run_mvn surefire:test -P enable-slf4j-2.x
run_mvn dependency:properties surefire:test -P enable-ttl-agent-for-test -P enable-slf4j-2.x
